package com.czmh.etc.onlinepubsys.configuration;

import com.czmh.etc.onlinepubsys.interceptors.JwtInterceptor;
import com.czmh.etc.onlinepubsys.interceptors.LogInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * @描述：WebConfig
 * @author： Seven.
 * @创建日期：2019年06月25日18:41:38
 * @版本：1.0.0
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Autowired
    private PropertyConfig propertyConfig;
    @Value("${html.static-locations}")
    private String staticLocations;

    @Value("${spring.profiles.active}")
    private String active;

    @Bean
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new CustomRequestMappingHandlerMapping();
        handlerMapping.setOrder(0);
        handlerMapping.setInterceptors(getInterceptors());
        return handlerMapping;
    }

    /**
     * 再拦截器中使用了RedisUtil bean类，但是拦截器执行实在spring容器bean初始化之前的
     * RedisUtil 将无法注入，为了解决该问题，将JwtInterceptor拦截器先配置为一个bean
     * 在注册拦截器时，直接使用配置的bean
     */
    @Profile({"pro","test"})
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 通过对环境变量的判断确定是否打开jwt校验
         */
        registry.addInterceptor(new LogInterceptor());
        if(active.equalsIgnoreCase("pro") || active.equalsIgnoreCase("test")){
            registry.addInterceptor(jwtInterceptor()).excludePathPatterns(propertyConfig.getExcludePaths());
        }
    }

    /**
     * swagger静态文件路径过滤,否则版本控制会拦截
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("file:" + staticLocations);
        super.addResourceHandlers(registry);
    }
}